import axios from 'axios'
import * as Constant from '../constant'

const getToken = () => {
    return localStorage[Constant.TOKEN_KEY]
}

// 发送请求之前
axios.interceptors.request.use(
    conf => {
        const token = getToken()
        if (token) {
            conf.headers.common['Authorization'] = `Bearer ` + token
        }
        return conf
    },
    err => Promise.reject(err)
)

// 发送请求之后
axios.interceptors.response.use(
    response => {
        let res = response.data
        if (res.code === 401) {
            console.error('token 失效')
            return Promise.reject(response.data)
        } else {
            return Promise.resolve(response.data)
        }
    },
    err => Promise.reject(err)
)

export default (url, options) => {
    let res = axios(`/api${url}`, options)
    return res
}
